// 字符串转为ArrayBuffer
let str2ab = (str) => {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i = 0; i < str.length; i++) {
    bufView[i] = str.charCodeAt(i)
  }
  console.log('字符串转ab：', buf)
  return buf
}
// 字符串转16进制
let str2Hex = (str) => {
  let array = new Uint8Array(str.length)
  for (let i = 0; i < str.length; i++) {
    array[i] = str.charCodeAt(i)
  }
  console.log('array', array)
  return array.buffer
}
// 16进制字符串转ArrayBuffer    
let hex2ab = (hex_str) => {
  // let hex_str = 'AA5504B10000B5'      
  let typedArray = new Uint8Array(hex_str.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  }))
  let buffer = typedArray.buffer
  return buffer
}

// 16进制字符串转字符串   
let hex2str = (hex_str) => {
  let trimedStr = hex_str.trim();
  let rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
  let len = rawStr.length;
  if (len % 2 !== 0) {
    console.log("Illegal Format ASCII Code!");
    return "";
  }
  let curCharCode;
  let resultStr = [];
  for (let i = 0; i < len; i = i + 2) {
    curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value      
    resultStr.push(String.fromCharCode(curCharCode));
  }
  return resultStr.join("");
}

// json字符串数据转Uint8Array
let str2Uint8Array = (str) => {
  var arr = [];
  for (var i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
  var tmpUint8Array = new Uint8Array(arr);
  return tmpUint8Array
}

// ArrayBuffer转为字符串，参数为ArrayBuffer对象
let ab2str = (buf) => {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}

// ArrayBuffer转16进制字符串
let ab2hex = (buffer) => {
  let hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
module.exports = {
  str2ab,
  str2Hex,
  hex2ab,
  hex2str,
  ab2str,
  ab2hex,
  str2Uint8Array
}